package com.onlyxiahui.wofa.server.socket.netty.websocket.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.onlyxiahui.framework.action.dispatcher.general.GeneralMessageHandler;
import com.onlyxiahui.wofa.server.net.core.session.SocketSessionHandler;
import com.onlyxiahui.wofa.server.socket.netty.common.handler.SessionDataHandler;
import com.onlyxiahui.wofa.server.socket.netty.websocket.session.WebSocketSession;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	private WebSocketSession webSocketSession;
	private SocketSessionHandler sessionHandler;
	private SessionDataHandler sessionDataHandler;

	public WebSocketFrameHandler(GeneralMessageHandler messageHandler, SocketSessionHandler sessionHandler) {
		this.sessionHandler = sessionHandler;
		this.sessionDataHandler = new SessionDataHandler(sessionHandler, messageHandler);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
		String data = null;
		try {
			if (frame instanceof TextWebSocketFrame) {
				data = ((TextWebSocketFrame) frame).text();
				sessionDataHandler.message(webSocketSession, data);
			}
		} catch (Exception e) {
			sessionHandler.dataException(webSocketSession, data, e);
			logger.error("", e);
		}
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		webSocketSession = new WebSocketSession(ctx);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		sessionHandler.sessionRemove(webSocketSession);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug((null != webSocketSession) ? webSocketSession.getKey() : "" + "：空闲");
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// cause.printStackTrace();
		// ctx.close();
		logger.error("", cause);
	}
}
